<template>
  <rk-dialog width="80%"
    height="80%"
    :title="title"
    :visible="visible"
    @close="visible = false"
    :maskClosable="false"
    :destroyOnClose="true">
    <unit-form ref="unitFormRef"
      :unitModel="unitModel"
      :model="model"></unit-form>
    <template #footer>
      <el-button type="primary"
        @click="handleConfirm">保存</el-button>
      <el-button @click="hanldeClose">取消</el-button>
    </template>
  </rk-dialog>
</template>
  <script setup>
import { nextTick, ref } from 'vue'
import UnitForm from '../form/UnitForm.vue'
import { useUnitApi } from '@/api/index.js'
import { ElLoading, ElMessage } from 'element-plus'

const { savePubagency } = useUnitApi();
const emit = defineEmits(['confirm'])
const treeParams = inject('treeParams')
let visible = ref(false)
const unitFormRef = ref('')
const title = ref('填写单位信息',)
let unitModel = reactive({})
const model = ref('')
/** 打开弹出层 */
const handleOpen = async (options) => {
  visible.value = true
  const { model: opration, unitModel: seleModel } = options
  if (opration === 'add') {
    unitModel = {}
    title.value = '填写单位信息'
  } else if (opration == 'edit') {
    title.value = "修改单位信息"
    unitModel = {
      ...seleModel
    }
  }
  model.value = opration
  await nextTick()
  unitFormRef.value.loadForm()

}
/** 关闭弹窗 */
const hanldeClose = () => {
  visible.value = false
  unitFormRef.value.resetForm()
}
/** 重置表单 */
const handleHide = () => {
  unitFormRef.value.resetForm()
}
/** 确认提交 */
const handleConfirm = async () => {
  const params = { ...treeParams }
  const { agCode, adCode } = params
  const validate = await unitFormRef.value.validateForm()
  if (validate) {
    const formData = unitFormRef.value.getFormData()
    formData.province = adCode
    if (model.value != 'edit') {
      if (agCode && agCode != '') {
        formData.code = agCode + formData.code
      } else {
        formData.code = formData.supdep + formData.code
      }
    }
    const loading = ElLoading.service({ fullscreen: true })
    const result = await savePubagency(formData)
    const { data, code, msg } = result
    if (code === 200) {
      loading.close()
      visible.value = false
      emit('confirm')
      ElMessage({
        message: '保存成功！',
        type: 'success',
      })
      handleHide()
    } else {
      ElMessage({
        message: msg,
        type: 'error',
      })
      loading.close()
      console.error(msg)
    }
  }
}
// 对外暴露方法
defineExpose({
  handleOpen,
})

</script>

<style lang="scss" scoped>
</style>
